package com.lighting.common.log;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import net.logstash.logback.appender.LogstashTcpSocketAppender;
import net.logstash.logback.encoder.LogstashEncoder;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
@ComponentScan(basePackages = "com.lighting.common.log")
public class LogConfiguration {

    @Value("${spring.application.name:}")
    private String appName;
    @Value("${lighting.common.log.logstash_url:}")
    private String logstashUrl;
    @Value("${lighting.common.log.queue_size:8192}")
    private int queueSize;

    @Bean
    public void logstashTcpSocketAppender() {
        if (StringUtils.isEmpty(logstashUrl)) {
            return;
        }
        ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
        if ("ch.qos.logback.classic.LoggerContext".equals(loggerFactory.getClass().getName())) {
            LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            Logger rootLogger = context.getLogger("root");

            LogstashEncoder encoder = new LogstashEncoder();
            encoder.setContext(context);
            encoder.setCustomFields("{\"appName\":\"" + appName + "\"}");
            encoder.addIncludeMdcKeyName(TraceConstant.MDC_TRACE_ID);
            encoder.addIncludeMdcKeyName(TraceConstant.MDC_SPAN_ID);
            encoder.start();

            LogstashTcpSocketAppender appender = new LogstashTcpSocketAppender();
            appender.setContext(context);
            appender.addDestination(logstashUrl);
            appender.setRingBufferSize(queueSize);
            appender.setEncoder(encoder);
            appender.start();

            rootLogger.addAppender(appender);
        }
    }
}
